/**
 * 用户模型
 * @module models/User
 */

const { DataTypes } = require('sequelize');
const bcrypt = require('bcrypt');
const { sequelize } = require('../config/database');

/**
 * 用户模型定义
 * @typedef {Object} User
 * @property {string} username - 用户名
 * @property {string} password - 密码(加密存储)
 * @property {string} email - 邮箱
 * @property {string} role - 角色(admin)
 */
const User = sequelize.define('User', {
  username: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      notEmpty: true,
      len: [3, 30]
    }
  },
  password: {
    type: DataTypes.STRING,
    allowNull: false,
    validate: {
      notEmpty: true,
      len: [6, 100]
    }
  },
  email: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
    validate: {
      isEmail: true
    }
  },
  role: {
    type: DataTypes.STRING,
    allowNull: false,
    defaultValue: 'admin',
    validate: {
      isIn: [['admin']]
    }
  }
}, {
  hooks: {
    /**
     * 保存前对密码进行加密
     * @param {User} user - 用户实例
     */
    beforeCreate: async (user) => {
      if (user.password) {
        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(user.password, salt);
      }
    },
    /**
     * 更新前对密码进行加密
     * @param {User} user - 用户实例
     */
    beforeUpdate: async (user) => {
      if (user.changed('password')) {
        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(user.password, salt);
      }
    }
  }
});

/**
 * 验证密码是否正确
 * @param {string} password - 明文密码
 * @returns {Promise<boolean>} 密码是否匹配
 */
User.prototype.validatePassword = async function(password) {
  return await bcrypt.compare(password, this.password);
};

module.exports = User; 